package com.tanhua.sso.service.impl;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.sso.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    /**
     * 用户登录
     *
     * @param phone
     * @param code  //验证码
     * @return
     */
    @Override
    public String login(String phone, String code) {
        String redisKey = "CHECK_CODE_" + phone;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        boolean isNew = false;
        //JWT 所需要的密钥，设置为明文
        //String secret = "itcast";
        //校验验证码
        if (!StringUtils.equals(code, redisData)) {
            //如果不相等，验证码错误
            return null;
        }
        //校验码在校验完成后需要删除
        this.redisTemplate.delete(redisKey);
        //验证手机号是否存在
        //查询数据库中是否有当前手机号信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        User user = this.userMapper.selectOne(queryWrapper);
        if (user == null) {
            //当前用户为新用户，需要注册
            //设置当前注册用户的基本信息
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            //用户注册
            this.userMapper.insert(user);
            isNew = true;

            //注册环信用户
            Boolean flag = this.huanXinApi.register(user.getId());
            if (!flag) {
                //注册失败
                log.error("注册环信用户失败~ userId = " + user.getId());
            }
        }

        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        //生成token时省略header ，header为默认配置方式
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, secret)
                .setExpiration(new DateTime().plusMinutes(14400).toDate())
                .compact();

        try {
            //发送用户登录成功的消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("date", System.currentTimeMillis());

            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (MessagingException e) {
            log.error("发送消息失败！", e);
        }

        return token + "|" + isNew;
    }

    @Override
    public User queryUserByToken(String token) {
        try {
            User user = new User();
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            //设置id在user中
            user.setId(Long.valueOf(body.get("id").toString()));

            /**
             * 需要返回对象中的mobile，需要查询数据库来获得数据
             * 如果每次查询数据库，必然导致性能问题，需要对用户的手机号进行缓存操作，
             * 数据缓存时，需要设置过期时间，并且过期时间要与token相同
             */
            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            if (this.redisTemplate.hasKey(redisKey)) {
                String mobile = this.redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            } else {
                //不存在时，查询数据库获得mobile
                User u = this.userMapper.selectById(user.getId());
                //设置mobile
                user.setMobile(u.getMobile());
                //将手机号写入Redis中，
                //在jwt中的过期时间单位为：秒
                long timeout = Long.valueOf(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
                this.redisTemplate.opsForValue().set(redisKey, user.getMobile(), timeout, TimeUnit.MILLISECONDS);
            }
            System.out.println(body);
            return user;

        } catch (ExpiredJwtException e) {
            log.info("token已经过期！token = " + token);
            //System.out.println("token已经过期！");
        } catch (Exception e) {
            //System.out.println("token不合法！！");
            log.error("token不合法！！ token = " + token, e);
        }
        return null;
    }

    /**
     * 保存新手机号
     *
     * @param userId
     * @param newPhone
     * @return
     */
    @Override
    public Boolean updatePhone(Long userId, String newPhone) {
        try {
            //先查询新手机号是否已经注册，如果已经注册，就不能修改
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("mobile", newPhone);
            User user = this.userMapper.selectOne(queryWrapper);
            if (Optional.ofNullable(user).isPresent()) {
                //号码已经存在，保存失败
                return false;
            }
            user = new User();
            user.setId(userId);
            user.setMobile(newPhone);

            return this.userMapper.updateById(user) > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
